#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2019/2/19 10:49
@desc
"""

import socket  # 导入 socket 模块

s = socket.socket()  # 创建 socket 对象
host = socket.gethostname()  # 获取本地主机名
port = 12345  # 设置端口
s.bind((host, port))  # 绑定端口
s.setblocking(False)
s.listen(5)  # 等待客户端连接

conn_l = set()
del_conn = set()
while True:
    try:
        c, addr = s.accept()  # 建立客户端连接。 不阻塞，但没人连接会报错
        print('连接地址：%s' % str(addr))
        c.send('欢迎访问luyaran！')
        conn_l.add(c)
    except socket.error as e:
        for c in conn_l:
            try:
                msg = c.recv(1024)    # 非阻塞，如果没有消息就阻塞
                if msg == b'':
                    del_conn.add(c)
                    continue
                print(msg)
                c.send('byebye')
            except socket.error:
                pass
        for dc in del_conn:
            dc.close()
            conn_l.remove(dc)
        del_conn.clear()

